<template>
  <!--毕业设计（论文）学生名单-->
  <div class="stu-list">
    <InnerBreadcrumb v-model="indexKey" :path="breadPath" :showBack="true" />
    <!--选择课程弹框-->
    <CourseDialog ref="courseDialog" @courseSubmit="courseSubmit" @courseClose="courseClose" :calendarId="queryForm.calendarId" :courseDialogVisible="dialogVisible"></CourseDialog>
    <div class="edu-page-warp" v-show="indexKey === 'MAIN'">
      <condition-card @reset="reset" @search="searchList" label-width="110px">
        <el-row>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.grade')">
              <el-date-picker class="search-item" clearable v-model="queryForm.gradeId" @change="handleGradeChange" value-format="yyyy" type="year" :placeholder="$t('graduationDesign.pleaseChoose')">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.college')">
              <el-select v-model="queryForm.collegeId" @change="handleCollegeChange" filterable class="search-item" clearable>
                <el-option v-for="item in source.collegeOptions" :key="item.collegeId" :label="item.collegeIdI18n" :value="item.collegeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item :label="$t('graduationDesign.major')">
              <el-select v-model="queryForm.subjectId" filterable class="search-item" clearable>
                <el-option v-for="item in source.subjectOptions" :key="item.subjectId" :label="item.subjectIdI18n" :value="item.subjectId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>
      <el-card shadow="never">
        <div class="edu-page-title">{{schoolCalendarInfo.perYear}}{{$t('graduationDesign.designTopicResultImport')}}</div>
        <div class="edu-opertion-bar">
          <div class="float-right">
            <el-button @click="onChooseCourse" v-loading.fullscreen.lock="loading" element-loading-text="Loading" element-loading-spinner="el-icon-loading" element-loading-background="rgba(255, 255, 255, .48)">{{$t('graduationDesign.chooseCourse')}}</el-button>
          </div>
        </div>
        <edu-table ref="designStuListTable" :url="getList" :selection="false" :order="false" v-if="isShowStuList">
          <edu-table-column :label="$t('graduationDesign.grade')" prop="gradeId" min-width="70"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.college')" prop="collegeIdI18n" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.major')" prop="subjectIdI18n" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.courseNum')" prop="teachingClassCode" min-width="90"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.courseName')" prop="courseName" min-width="100"></edu-table-column>
          <edu-table-column :label="$t('graduationDesign.selectedStudent')" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="onSelectedStu(scope.row)">{{scope.row.selectedStudentNum}}</el-button>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('graduationDesign.unselectedStudent')" min-width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="onUnselectedStu(scope.row)">{{scope.row.unselectedStudentNum}}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <hr v-if="!isShowStuList" />
        <div class="stu-footer" v-if="!isShowStuList">
          <div class="stu-text">{{$t('graduationDesign.clickSelectStudent')}}</div>
        </div>
      </el-card>
    </div>
    <div v-show="indexKey === 'SELECTED_STU'">
      <!--已选学生-->
      <StudentList :studentData="selectedStudentList" :studentInfo="selectedStuInfo" @stu-export="onExport"></StudentList>
    </div>
    <div v-show="indexKey === 'UNSELECTED_STU'">
      <!--未选学生-->
      <StudentList :studentData="unselectedStudentList" :studentInfo="unselectedStuInfo" @stu-export="onExport"></StudentList>
    </div>
  </div>
</template>
<script>
  import API from "common/src/api/underGraduationDesign/designStudentList";
  import tools from 'common/src/views/underGraduationDesign/tools.js';

  export default {
    name: 'designStudentList',
    data() {
      return {
        getList: '/api/designservice/CourseSelection/list',
        api: API,
        queryForm: {
          gradeId: '',
          collegeId: '',
          subjectId: '',
          calendarId: '',
          activeAuthId: ''
        },
        source: {
          collegeOptions: [], // 学院
          subjectOptions: [] // 专业
        },
        indexKey: 'MAIN',
        breadPath: {
          label: this.$t('graduationDesign.designStudentList'),
          key: "MAIN",
          children: [
            {
              key: "SELECTED_STU",
              label: this.$t('graduationDesign.selectedStudent')
            },
            {
              key: "UNSELECTED_STU",
              label: this.$t('graduationDesign.unselectedStudent')
            }
          ]
        },
        loading: false,
        isShowStuList: true, // 列表是否显示
        selectedStudentList: [],
        selectedStuInfo: {}, // 已选学生信息
        unselectedStudentList: [],
        unselectedStuInfo: {}, // 未选学生信息
        dialogVisible: false,
        schoolCalendarInfo: {} // 校历信息
      };
    },
    mounted() {
      this.getCollege();
      this.getCalendarInfo();
    },
    methods: {
      async searchList() {
        this.isShowStuList = true;
        await new Promise(resolve => setTimeout(resolve, 1000)); // 等待列表dom加载
        await this.$refs.designStuListTable.search(this.queryForm);
        if (this.$refs.designStuListTable.dataList.length === 0) {
          this.isShowStuList = false;
        }
      },
      reset() {
        this.queryForm.gradeId = "";
        this.queryForm.collegeId = "";
        this.queryForm.subjectId = "";
        this.source.subjectOptions = [];
        this.searchList();
      },
      // 查校历信息
      async getCalendarInfo() {
        const calendarInfo = await this.getCalendarId();
        //TODO 王国民老师提出毕业设计有成绩未导入，需修改至上学期
        this.schoolCalendarInfo = await this.getSchoolCalendar(calendarInfo.id -1 );
        this.queryForm.calendarId = this.schoolCalendarInfo.id;
        if (this.schoolCalendarInfo.perTerm === "第1学期") {
          this.queryForm.calendarId = this.schoolCalendarInfo.id + 1;
        }
        this.queryForm.activeAuthId = localStorage.getItem("activeAuthId");
        this.searchList();
      },
      getCalendarId() {
        return this.api.getCalendarId().then(res => {
          return res.data.schoolCalendar;
        }).catch();
      },
      getSchoolCalendar(calendarId) {
        return this.api.getSchoolCalendar(calendarId).then(res => {
          return res.data;
        });
      },
      // 查学院
      getCollege() {
        this.api.getCollege().then(res => {
          this.source.collegeOptions = res;
        });
      },
      // 毕业年份change
      handleGradeChange(val) {
        this.queryForm.subjectId = "";
        this.source.subjectOptions = [];
        if (val && this.queryForm.collegeId) {
          this.handleCollegeChange(this.queryForm.collegeId);
        }
      },
      // 根据年份学院查专业
      handleCollegeChange(val) {
        this.queryForm.subjectId = "";
        this.source.subjectOptions = [];
        if (val && this.queryForm.gradeId) {
          this.api.getSubject(val, this.queryForm.gradeId).then(res => {
            this.source.subjectOptions = res.data;
          }).catch();
        }
      },
      // 选择课程
      onChooseCourse() {
        this.dialogVisible = true;
        this.$nextTick(() => {
          this.$refs.courseDialog.clear();
        });
      },
      // 已选学生
      onSelectedStu(row) {
        this.indexKey = "SELECTED_STU";
        this.selectedStudentList = row.selectedStudentList;
        this.selectedStuInfo = {
          calendarId: this.queryForm.calendarId,
          college: row.collegeIdI18n,
          schoolYear: this.schoolCalendarInfo.perYear,
          studentType: "SELECTED_STU",
          studentTypeName: this.$t('graduationDesign.courseSelected')
        };
      },
      // 未选学生
      onUnselectedStu(row) {
        this.indexKey = "UNSELECTED_STU";
        this.unselectedStudentList = row.unselectedStudentList;
        this.unselectedStuInfo = {
          calendarId: this.queryForm.calendarId,
          college: row.collegeIdI18n,
          schoolYear: this.schoolCalendarInfo.perYear,
          studentType: "UNSELECTED_STU",
          studentTypeName: this.$t('graduationDesign.courseUnselected')
        };
      },
      // 导出
      onExport(data) {
        const stuList = data.list;
        const type = data.type === "SELECTED_STU" ? 1 : 0; // 已选1，未选0
        this.api.export(stuList, type).then(res => {
          const studentInfo = type === 1 ? this.selectedStuInfo : this.unselectedStuInfo;
          const fileName = studentInfo.schoolYear
            + studentInfo.college
            + this.$t('graduationDesign.graduationDesignCourseSelection')
            + '-'
            + studentInfo.studentTypeName
            + this.$t('graduationDesign.studentList')
            + '.xls';
          tools.downloadFile(res.data.key, fileName, this.api.getExportStatus, this);
          /*if (res.code == 200) {
            this.delayRequest(res.data.key);
          }*/
        });
      },
      // 查文件导出状态，等待导出
      async delayRequest(key) {
        this.loading = true;
        await new Promise(resolve => setTimeout(resolve, 3000));
        this.api.getExportStatus(key).then(res => {
          this.loading = false;
          if (res.code === 200 && res.data.status) {
            let path = 'api/designservice/common/export?path=' + res.data.path;
            window.open(path);
          } else {
            this.delayRequest(key);
          }
        }).catch(err => {
          this.loading = false;
          this.delayRequest(key);
        });
      },
      // 选择课程提交
      courseSubmit(data) {
        this.api.insertCourse(data).then(res => {
          this.$message.success(this.$t('graduationDesign.courseSubmitSuccess'));
          this.dialogVisible = false;
          this.searchList();
        }).catch();
      },
      courseClose() {
        this.dialogVisible = false;
      }
    },
    components: {
      StudentList: () => import('./components/studentList'),
      CourseDialog: () => import('./components/courseDialog')
    }
  }
</script>
<style lang="scss" scoped>
  .stu-list {
    .search-item {
      width: 100%;
    }
    .stu-footer {
      margin: 10px 0px;
      border-top: 1px solid #dcdfe6;
      border-bottom: 1px solid #dcdfe6;
      height: 300px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #f2f6fc;
      .stu-text {
        font-size: 18px;
        color: #dcdfe6;
      }
    }
  }
</style>
